package sc.client.world;

import java.io.IOException;

import k8.primitive.Triangle;
import sc.client.Client;
import sc.client.procedural.TileTexture;
import sc.datainterchange.CodedInputBuffer;

/**
 * Tile
 * 
 * @author Stephen Carmody
 */
public final class Tile extends Container
{
	// Tile object identity in data interchange
	private static final int OBJECTTYPEID = 2;
	
	public static int MAPSIZE = 1000;
	public static int WIDTH = 200 / Client.SCALE;
	public static int HALFMAPSIZE = (int) (Tile.MAPSIZE * 0.5);
	public static int HALFWIDTH = (int) (Tile.WIDTH * 0.5);

	// Grid of Tiles that make up the known world
	public static Tile[][] tiles = new Tile[Tile.MAPSIZE][Tile.MAPSIZE];

	// The tiles scene bounds
	public int left;
	public int top;
	public int right;
	public int bottom;

	/**
	 * Creates an instance of Tile.
	 */
	public Tile()
	{
	}

	/**
	 * Receives "object" data and either creates or updates the corresponding
	 * object.
	 * 
	 * @param dataEvent
	 */
	public void read(CodedInputBuffer codedinput) throws IOException
	{
		super.read(codedinput);

		Tile.tiles[this.getTileX()][this.getTileZ()] = this;

		// Set tiles scene bounds
		this.left = (int) this.T[3] - HALFWIDTH;
		this.top = (int) this.T[11] - HALFWIDTH;
		this.right = (int) this.T[3] + HALFWIDTH;
		this.bottom = (int) this.T[11] + HALFWIDTH;
		
		// Make a flat surface out of two Triangles
		Triangle triangle = new Triangle();
		triangle.setVertices(-Tile.HALFWIDTH , 0, Tile.HALFWIDTH,
				Tile.HALFWIDTH , 0, Tile.HALFWIDTH,
				Tile.HALFWIDTH, 0, -Tile.HALFWIDTH);
		triangle.setTexture(0, 1, 1, 1, 1, 0);
		triangle.setTexture(TileTexture.getInstance());
		this.add(triangle);

		triangle = new Triangle();
		triangle.setVertices(-Tile.HALFWIDTH, 0, Tile.HALFWIDTH,
				Tile.HALFWIDTH, 0, -Tile.HALFWIDTH,
				-Tile.HALFWIDTH, 0, -Tile.HALFWIDTH);
		triangle.setTexture(0, 1, 1, 0, 0, 0);
		triangle.setTexture(TileTexture.getInstance());
		this.add(triangle);
		
		Client.logger.info("tile at " + this.T[3] + ", " + this.T[11] + " - " + Tile.HALFWIDTH);
	}

	/**
	 * Gets the tile at the specified position.
	 * 
	 * @param x
	 * @param z
	 * 
	 * @return a Tile instance
	 */
	public static Tile get(int tilex, int tilez)
	{
		return tiles[tilex][tilez];
	}

	/**
	 * Gets the x index in tiles grid.
	 * 
	 * @return x index in tiles grid
	 */
	public int getTileX()
	{
		return (int) (this.T[3] / Tile.WIDTH) * Client.SCALE + Tile.HALFMAPSIZE;
	}

	/**
	 * Gets the z index in tiles grid.
	 * 
	 * @return z index int tiles grid
	 */
	public int getTileZ()
	{
		return (int) (this.T[11] / Tile.WIDTH) * Client.SCALE + Tile.HALFMAPSIZE;
	}

	@Override
	public String getID()
	{
		return "tile:" + getTileX() + "x" + getTileZ();
	}

}
